package com.lagou.homework.clientserverchat;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;
import java.util.Vector;

/**
 * @author Rentaian
 */
public class ServerThread extends Thread{
    private Socket s = null;

    public ServerThread(Socket ss) {
        this.s = ss;
    }

    @Override
    public void run() {
        BufferedReader br = null;
        PrintStream ps = null;
        List<Socket> ls = Servers.ls;
        Scanner sc = null;
        try {
            sc = new Scanner(System.in);
            System.out.println("等待客户端的连接！");
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));
            ps = new PrintStream(s.getOutputStream());

                while(true) {
                    String str1 = br.readLine();



                    System.out.println("客户端说"+ s.getInetAddress()+"说: " + str1);

                    System.out.println("收到客户端:" + s.getInetAddress() + "发来的信息！");
                    if("bye".equalsIgnoreCase(str1)) {
                        System.out.println("客户端:" + s.getInetAddress() + "已下线！");
                        break;
                    }

                    for (Socket sk : ls) {
                        ps = new PrintStream(sk.getOutputStream());
                        System.out.println("请输入要发送的信息！");
                        String str2 = sc.next();
                        ps.println(str2);
                        System.out.println("发送成功");
                    }
                }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(null != ps) {
                ps.close();
            }
            if(null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != s) {
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(null != sc) {
                sc.close();
            }
        }

    }
}
